package com.sh.rbac.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.rbac.core.common.exception.CustomException;
import com.sh.rbac.core.common.result.ResultCodeEnum;
import com.sh.rbac.domain.converter.DictConverter;
import com.sh.rbac.domain.dto.dict.DictQueryDTO;
import com.sh.rbac.domain.dto.dict.DictSaveDTO;
import com.sh.rbac.domain.dto.dict.DictUpdateDTO;
import com.sh.rbac.domain.entity.Dict;
import com.sh.rbac.domain.entity.DictItem;
import com.sh.rbac.mapper.DictItemMapper;
import com.sh.rbac.mapper.DictMapper;
import com.sh.rbac.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * @author lucky
 * @description 针对表【sys_dict(字典表)】的数据库操作Service实现
 * @createDate 2024-06-26 20:57:02
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
        implements DictService {

    @Autowired
    private DictItemMapper dictItemMapper;

    @Override
    public Page<Dict> getPage(Long current, Long limit, DictQueryDTO dictQueryDTO) {

        // 创建 page 对象，传递当前页, 每页记录数
        Page<Dict> page = new Page<>(current, limit);

        // 条件参数
        String name = dictQueryDTO.getName();
        String code = dictQueryDTO.getCode();
        Integer status = dictQueryDTO.getStatus();

        // 构建条件
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(name), Dict::getName, name)
                .like(StrUtil.isNotBlank(code), Dict::getCode, code)
                .eq(status != null, Dict::getStatus, status);

        // 根据修改时间倒序
        queryWrapper.orderByDesc(Dict::getUpdateTime);

        // 返回结果
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Boolean save(DictSaveDTO dictSaveDTO) {
        Dict dict = DictConverter.INSTANCE.toEntity(dictSaveDTO);
        return super.save(dict);
    }

    @Override
    public Boolean updateById(DictUpdateDTO dictUpdateDTO) {
        Dict dict = DictConverter.INSTANCE.toEntity(dictUpdateDTO);
        return super.updateById(dict);
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        Dict dict = new Dict();
        dict.setId(id);
        dict.setStatus(status);

        return super.updateById(dict);
    }

    @Override
    public boolean removeById(Serializable id) {
        List<DictItem> dictItems = dictItemMapper.selectList(new LambdaQueryWrapper<DictItem>().eq(DictItem::getId, id));
        if (!dictItems.isEmpty()) {
            throw new CustomException(ResultCodeEnum.NODE_HAS_CHILDREN);
        }

        return super.removeById(id);
    }

}




